import { DataSource, EntityManager } from 'typeorm';
import { WsRoom, WsRoomSocket, WsSocket } from './room';
import { SsoToken } from './sso.token';
import { SsoUser } from './sso.user';
import { ProxySetting } from './proxy';
import { SsoLog } from './log';

let ds: DataSource;

export interface EntityManagerHandler<T> {
    (m: EntityManager): Promise<T>;
}

export async function useEntityManager<T = any>(h: EntityManagerHandler<T>) {
    const ds = await useDataSource()
    const m = ds.createEntityManager()
    return m.transaction(h)
}

export async function useDataSource() {
    if (ds) {
        if (ds.isInitialized) return ds;
        await ds.initialize()
        return ds;
    }
    const url = process.env.DATABASE_URL
    ds = new DataSource({
        type: 'postgres',
        url: url,
        entities: [
            WsRoom,
            WsSocket,
            WsRoomSocket,
            SsoToken,
            SsoUser,
            ProxySetting,
            SsoLog
        ],
        synchronize: process.env.NODE_ENV === 'development'
    })
    await ds.initialize()
    return ds;
}

export { 
    WsRoom,
    WsSocket,
    WsRoomSocket,
    SsoToken,
    SsoUser,
    ProxySetting,
    SsoLog
}